package com.example.demo.nuoqi.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.example.demo.nuoqi.pojo.*;
import com.example.demo.nuoqi.service.ApplicationService;
import com.example.demo.nuoqi.service.InviteapplicationService;
import com.example.demo.nuoqi.service.ItemdetailsService;
import com.example.demo.nuoqi.service.UserService;
import com.example.demo.nuoqi.utils.JsonUtils;
import com.example.demo.nuoqi.utils.Result;
import com.example.demo.nuoqi.utils.StatusCode;
import com.example.demo.nuoqi.utils.UserUtils;
import com.github.pagehelper.PageInfo;

import io.swagger.annotations.*;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/****
 * @Author:shenkunlin
 * @Description:
 * @Date 2019/6/14 0:18
 *****/
@Api(value = "ApplicationController")
@RestController
@RequestMapping("/application")
@CrossOrigin
public class ApplicationController {

    @Autowired
    private ApplicationService applicationService;
    @Autowired
    UserService userService;
    @Autowired
    ItemdetailsService itemdetailsService;
    @Autowired
    InviteapplicationService inviteapplicationService;

    /***
     * Application分页条件搜索实现
     * @param application
     * @param page
     * @param size
     * @return
     */
    @ApiOperation(value = "Application条件分页查询",notes = "分页条件查询Application方法详情",tags = {"ApplicationController"})
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "page", value = "当前页", required = true, dataType = "Integer"),
            @ApiImplicitParam(paramType = "path", name = "size", value = "每页显示条数", required = true, dataType = "Integer")
    })
    @PostMapping(value = "/search/{page}/{size}" )
    public Result<PageInfo> findPage(@RequestBody(required = false) @ApiParam(name = "Application对象",value = "传入JSON数据",required = false) Application application, @PathVariable int page, @PathVariable int size){
        //调用ApplicationService实现分页条件查询Application
        PageInfo<Application> pageInfo = applicationService.findPage(application, page, size);
        return new Result(true, StatusCode.OK,"查询成功",pageInfo);
    }

    /***
     * Application分页搜索实现
     * @param page:当前页
     * @param size:每页显示多少条
     * @return
     */
    @ApiOperation(value = "Application分页查询",notes = "分页查询Application方法详情",tags = {"ApplicationController"})
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "page", value = "当前页", required = true, dataType = "Integer"),
            @ApiImplicitParam(paramType = "path", name = "size", value = "每页显示条数", required = true, dataType = "Integer")
    })
    @GetMapping(value = "/search/{page}/{size}" )
    public Result<PageInfo> findPage(@PathVariable int page, @PathVariable int size){
        //调用ApplicationService实现分页查询Application
        PageInfo<Application> pageInfo = applicationService.findPage(page, size);
        return new Result<PageInfo>(true,StatusCode.OK,"查询成功",pageInfo);
    }

    /***
     *
     * @param application
     * @return
     */
    @ApiOperation(value = "Application条件查询",notes = "条件查询Application方法详情",tags = {"ApplicationController"})
    @PostMapping(value = "/search" )
    public Result<List<Application>> findList(@RequestBody(required = false) @ApiParam(name = "Application对象",value = "传入JSON数据",required = false) Application application){
        //调用ApplicationService实现条件查询Application
        List<Application> list = applicationService.findList(application);
        return new Result<List<Application>>(true,StatusCode.OK,"查询成功",list);
    }

    /***
     * 根据ID删除品牌数据
     * @param id
     * @return
     */
    @ApiOperation(value = "Application根据ID删除",notes = "根据ID删除Application方法详情",tags = {"ApplicationController"})
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", required = true, dataType = "Integer")
    @DeleteMapping(value = "/{id}" )
    public Result delete(@PathVariable Integer id){
        //调用ApplicationService实现根据主键删除
        applicationService.delete(id);
        return new Result(true,StatusCode.OK,"删除成功");
    }

    /***
     * 修改Application数据
     * @param application
     * @param id
     * @return
     */
    @ApiOperation(value = "Application根据ID修改",notes = "根据ID修改Application方法详情",tags = {"ApplicationController"})
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", required = true, dataType = "Integer")
    @PutMapping(value="/{id}")
    public Result update(@RequestBody @ApiParam(name = "Application对象",value = "传入JSON数据",required = false) Application application, @PathVariable Integer id){
        //设置主键值
        application.setId(id);
        //调用ApplicationService实现修改Application
        applicationService.update(application);
        return new Result(true,StatusCode.OK,"修改成功");
    }

    /***
     * 新增Application数据
     * @param application
     * @return
     */
    @ApiOperation(value = "Application添加",notes = "添加Application方法详情",tags = {"ApplicationController"})
    @PostMapping
    public Result add(@RequestBody @ApiParam(name = "Application对象",value = "传入JSON数据",required = true) Application application, HttpSession session){
        //调用ApplicationService实现添加Application
        User user =(User) session.getAttribute("user");
        application.setId(user.getId());
        application.setUserName(user.getName());
        applicationService.add(application);
        return new Result(true,StatusCode.OK,"添加成功");
    }

    /***
     * 根据ID查询Application数据
     * @param id
     * @return
     */
    @ApiOperation(value = "Application根据ID查询",notes = "根据ID查询Application方法详情",tags = {"ApplicationController"})
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", required = true, dataType = "Integer")
    @GetMapping("/{id}")
    public Result<Application> findById(@PathVariable Integer id){
        //调用ApplicationService实现根据主键查询Application
        Application application = applicationService.findById(id);
        return new Result<Application>(true,StatusCode.OK,"查询成功",application);
    }

    /***
     * 查询Application全部数据
     * @return
     */
    @ApiOperation(value = "查询所有Application",notes = "查询所Application有方法详情",tags = {"ApplicationController"})
    @GetMapping
    public Result<List<Application>> findAll(){
        //调用ApplicationService实现查询所有Application
        List<Application> list = applicationService.findAll();
        return new Result<List<Application>>(true, StatusCode.OK,"查询成功",list) ;
    }


    @ApiOperation(value = "获取邀请项目列表",notes = "获取邀请项目列表",tags = {"ApplicationController"})
    @GetMapping("/getBeApplicationJoinItemList")
    public Result<List<Myapplication>> getBeApplicationJoinItemList(HttpSession session){
        //获取当前登录用户
        User user = UserUtils.getUser(session);
        List<Application> applicationServiceAll = applicationService.findAll();
        ArrayList<Application> list = new ArrayList<>();
        for (Application application : applicationServiceAll) {
            if ("1".equals(application.getStatus())  && user.getId() == Integer.valueOf(application.getItemInvite())) {
                list.add(application);
            }
        }
        return new Result(true, StatusCode.OK,"获取被邀请加入项目列表成功",list) ;
    }


    /***
     * 设置审批结果
     * @return
     */
    @ApiOperation(value = "设置审批结果",notes = "设置审批结果方法详情",tags = {"ApplicationController"})
    @GetMapping("setBeApplicationResult/{chooseId}/{result}")
    public Result setBeApplicationResult(@PathVariable("chooseId") Integer id,@PathVariable("result")String result,HttpSession session){
        Application application = applicationService.findById(id);
        application.setStatus(result);
        User user = UserUtils.getUser(session);


        Itemdetails itemdetails = itemdetailsService.findById(Integer.valueOf(application.getApproveApplication()));

        Itemdetails.participantTemp temp = new Itemdetails.participantTemp();

        temp.setUserId(user.getId());
        temp.setUserName(user.getName());


        List<Itemdetails.participantTemp> tempList = new ArrayList<>();

        // 同意邀请
        if (result.equals("2")) {
            // 有参与人
            if (null != itemdetails.getParticipant()  && !"".equals(itemdetails.getParticipant())) {
                List<Itemdetails.participantTemp> toList = JsonUtils.jsonToList(itemdetails.getParticipant(), Itemdetails.participantTemp.class);
                if (toList.size() < itemdetails.getItemPersonNum()) {
                    toList.add(temp);
                    String json = JsonUtils.objectToJson(toList);
                    itemdetails.setParticipant(json);
                    itemdetailsService.update(itemdetails);
                }else{
                    return new Result(false, StatusCode.ERROR,"被邀请项目人数已满",null) ;
                }
            }else{
                tempList.add(temp);
                itemdetails.setParticipant(JsonUtils.objectToJson(tempList));
                itemdetailsService.update(itemdetails);
            }
            applicationService.update(application);
            return new Result(true, StatusCode.OK,"以同意加入被邀请项目",null) ;
        }

        applicationService.update(application);
        return new Result(true, StatusCode.OK,"被邀请审批完成",null) ;
    }

    @ApiOperation(value = "查询当前用户被邀请列表",notes = "查询当前用户被邀请列表",tags = {"ApplicationController"})
    @GetMapping("findByUserApplicationedList")
    public Result findByUserApplicationedList(HttpSession session) {
        User user = UserUtils.getUser(session);
        List<Application> all = applicationService.findAll();
        List<Application> temp = new ArrayList<>();
        for (Application application : all) {
            if (application.getUserId() == user.getId()) {
                User id = userService.findById(Integer.valueOf(application.getItemInvite()));
                application.setItemInviteUser(id);
                Itemdetails itemdetails = itemdetailsService.findById(Integer.valueOf(application.getApproveApplication()));
                application.setItemdetails(itemdetails);

                Inviteapplication inviteapplication = inviteapplicationService.findById(Integer.valueOf(application.getMyApplication()));


                application.setInviteDate(inviteapplication.getCreateTime());
                temp.add(application);
            }
        }

        return new Result(true, StatusCode.OK,"查询当前用户被邀请列表",temp) ;
    }

    @ApiOperation(value = "申请退出项目",notes = "申请退出项目",tags = {"ApplicationController"})
    @GetMapping("/ApplicationQuitItem/{chooseId}/{result}")
    public Result ApplicationQuitItem(@PathVariable("chooseId") Integer id,@PathVariable("result")String result,HttpSession session) {
        Application application = applicationService.findById(id);
        Inviteapplication inviteapplication = inviteapplicationService.findById(Integer.valueOf(application.getMyApplication()));
        application.setStatus(result);
        inviteapplication.setStatus(result);
        applicationService.update(application);
        inviteapplicationService.update(inviteapplication);
        return new Result(true, StatusCode.OK,"申请退出项目成功,等待审批",null) ;
    }


}
